var form = layui.form,table = layui.table, $ = layui.jquery, upload = layui.upload, id = getQueryVariable("id"),annexList = [];
var data0 = [];
var data1 = [];
var data2 = [];
var data3 =[];
var isContainsRole=false;
getIsContainsRole();

//日志标签 有权限:false 无权限:true
let LogLabel = getAllRolesByCurr("LogLabel");

$('#editor-form').find('input,textarea,select').attr('disabled',true);

//表单初始值，修改时调用
if (id != "") {
    form.val("editor-form", {
        "invoicenumber": "进入查看明细",
    })
}
var bill=[];
var products=[];
var    parts=[];
$(document).ready(function () {

    getInfo()
    table.reload('storageproductstableid',{
        data:products
    })
    showInfo()
        //加载附件
        $.ajax({
            url: 'billChange/selectBillFile?type=2&parentId='+id,
            type: 'GET',
            success: function (date) {
                annexList = date.data;
                table.reload('attachmenttableid', {data:date.data});;
            }
        });
})
function  showInfo() {
    var info=bill[0]
    $("input[name='customername']").val(info.customerName);
    $("input[name='idate']").val(info.invoiceDate);
    $("input[name='shdate']").val(info.shippingDate);
    $("input[name='edrdate']").val(info.settleDate);
    $("input[name='invoicenumber']").val(info.invoiceNo);
    $("input[name='currency']").val(info.moneyKind);
    $("input[name='exchangerate']").val(info.usdRate);
    $("input[name='rmbexchangerate']").val(info.rmbRate);
    $("input[name='place']").val(info.startPlace);
    $("input[name='destination']").val(info.endPlace);
    $("input[name='settlementway']").val(info.settleMode);
    $("input[name='priceterms']").val(info.priceTerm);
    $("input[name='invoicetotalamount']").val(info.invoiceMoney);
    $("input[name='salescontractno']").val(info.contractNo);
    $("input[name='customercontractno']").val(info.custContractNo);
    $("input[name='salesman']").val(info.salesman);
    $("input[name='businessmodel']").val(info.businessMode);
    $("#asperinno").val(info.asPerInNo);
    $("input[name='warehouse']").val(info.stock);
    $("input[name='withinlimit']").val(info.overdue);
    $("input[name='containertype']").val(info.payday);
    $("input[name='signingcompany']").val(info.companyName);
    $("input[name='bank']").val(info.bankName);
    $("input[name='theoperator']").val(info.opname);
    $("input[name='totaltariffamount']").val(info.totalTariffAmount);
    $("input[name='actualdischargedateatd']").val(info.actualAtd);
    $("input[name='wldate']").val(info.instockDate);
    var s="否"
    if(info.whetherCreditGuarantee==1){
        s="是(采购抬头：上海沣奇)"
    }else if (info.whetherCreditGuarantee==2){
        s="是(采购抬头：上海源铢)"
    }
    $("input[name='whetherCreditGuarantee']").val(s);
    $("input[name='creditGuaranteeAmount']").val(info.creditGuaranteeAmount);
    form.render();
}
function getInfo(){
    $.ajax({
        url: 'billChange/selectInfoBillById?billId='+id,
        type: 'GET',
        async: false, // 同步
        success: function (date) {
            var map=date.data;
            $.each(map, function (key, value) {
                if(key=="bill"){
                    bill=value
                }
                if(key=="products"){
                    products=value
                }
                if(key=="parts"){
                    parts=value
                }
                if(key=="costs"){
                    var costs=value
                    table.reload('costtableid',{
                        data:costs
                    })
                }
            });
        }
    });
}


function getIsContainsRole(){
    $.ajax({
        url: 'billChange/isContainsRole',
        async: false, // 同步
        data: JSON.stringify(bill),
        success: function (date) {
            isContainsRole=date.data;
        }
    });
}
form.render();
//--产品信息
table.render({
    elem: '#storageproducts',
    id: 'storageproductstableid',
    data: data0,
    toolbar: '#storageproductstoolbar',
    totalRow: true,
    cols: [[
        {field: 'numbers',width: 50,type:'numbers',title:'序号', totalRowText: '合计'},
        {field: 'stockNo', width: 120, title: '采购单号'},
        {field: 'goodsCode', width: 120, title: '产品编码'},
        {field: 'specCode', width: 120, title: '规格编码'},
        {field: 'specNo', width: 120, title: '规格说明'},
        {field: 'goodsCname', width: 120, title: '中文名称'},
        {field: 'goodsEname', width: 120, title: '英文名称'},
        {field: 'goodsCdesc', width: 120, title: '中文描述'},
        {field: 'goodsEdesc', width: 120, title: '英文描述'},
        {field: 'goodsNum', width: 80, title: '产品数量'},
        {field: 'lastAmount', width: 140, title: '本次结汇数量'},
        {field: 'goodsUnit', width: 120, title: '单位'},
        {field: 'funitprice', width: 80, title: '单价'},
        {field: 'ftotalprice', width: 120, title: '金额小计', totalRow: true},
        {field: 'color', width: 120, title: '颜色'},
        {field: 'goodsGross', width: 120, title: '毛重'},
        {field: 'totalGross', width: 120, title: '毛重小计' },
        {field: 'netweight', width: 120, title: '净重'},
        {field: 'totalNet', width: 120, title: '净重小计'},
        {field: 'bulk', width: 120, title: '体积'},
        {field: 'totalBulk', width: 120, title: '体积小计'},
        {field: 'totalTray', width: 120, title: '托数'},
        {field: 'trayNum', width: 120, title: '每托量'},
        {field: 'piecesNum', width: 120, title: '件数'},
        {field: 'perpiecesNum', width: 120, title: '每件数量'},
        {field: 'paymentpaymentdays', width: 120, title: '付款账期'},
        {field: 'costUnitPrice', width: 120, title: '成品单价', totalRow: true,hide:!isContainsRole},
        {field: 'accessoriesCost', width: 120, title: '配件成本', totalRow: true,hide:!isContainsRole},
        {field: 'finishedProductCost', width: 120, title: '成品成本', totalRow: true,hide:!isContainsRole},
        {field: 'costSubtotal', width: 120, title: '成本小计',hide:!isContainsRole},
        {field: 'supplyerName', width: 120, title: '供应商',hide:!isContainsRole},
        {field: 'saleContractNo', width: 120, title: '外销合同号'},
        {field:'tariffRate', title:'关税税率', width: 120},
        {field:'tariffMoney', title:'关税金额', width: 120},
        {field:'lot', title:'批次', width: 120},
        {fixed: 'right', title: '操作', width: 120, align: 'center', toolbar: '#storageproductseditor'}
    ]],
    page: false,
    limit: Number.MAX_VALUE,
    height: 380
});
//监听行单击事件
table.on('row(storageproductstable)', function(obj){

    var billid= obj.data.billId
    var billProductId=obj.data.billProductId
    var showPart=[]
    for(let i in parts){
        if(parts[i].billId==billid&&parts[i].billProductId==billProductId){
            showPart.push(parts[i])
        }
    }
    $("#hidden").show();
    table.render({
        elem: '#productsaselect'
        ,data:showPart
        ,toolbar: '#productsatoolbar'
        ,where:{id:obj.data.id} //查询的产品ID，条件
        ,cols: [[
             {field: 'goodsCode', title: '产品编码'}
            ,{field: 'specCode', title: '规格编码'}
            ,{field:'cpbl', title:'成品比例'}
            ,{field:'pebl', title:'配件比例'}
            ,{field:'goodsnumParts', title:'配件数量'}
            ,{field:'lastAmount', title:'本次结汇数量',width: 140}
            ,{field: 'costUnitPrice', width: 120, title: '成本单价',hide:!isContainsRole}
            ,{field: 'costSubtotal', width: 120, title: '成本小计',hide:!isContainsRole}
            ,{field: 'stockNo', width: 120, title: '采购单号'}
            ,{field: 'supplyerName', width: 120, title: '供应商',hide:!isContainsRole}
            ,{field:'goodsCname', title:'中文名称'}
            ,{field:'goodsEname', title:'英文名称'}
            ,{field:'goodsGross', title:'毛重'}
            ,{field:'netWeight', title:'净重'}
            ,{field:'bulk', title:'体积'}
        ]]
        ,id: 'productsatableid'
        ,page: true
        ,height:300
    });
});
//---费用
table.render({
    elem: '#cost'
    , data: []
    , toolbar: '#costtoolbar'
    , cols: [[
        {checkbox: true, fixed: true}
        , {field: 'costType', title: '费用类型',templet: function(element){
                var  costType= element.costType
                var recost="";
                var cost= getCost();
                for(let i in cost){
                    $(".costType").append(new Option(cost[i].name,cost[i].code));
                    if(cost[i].code==costType){
                        recost=cost[i].name
                    }
                }
                return recost
        }}
        , {field: 'costMoney', title: '金额',event:'amount'}
        , {field: 'costDesc', title: '备注说明'}
        , {field: 'contractNo', title: '外销合同号'}
    ]]
    , id: 'costtableid'
    , height: 380
    , page: true
    , done: function (res, curr, count) {
        // $(".layui-table select").parent(".layui-table-cell").css('overflow','visible')
        // $(".layui-form-select").parents(".layui-table-cell").css('overflow','visible')
        // var cost= getCost();
        // for(let i in cost){
        //     $(".costType").append(new Option(cost[i].name,cost[i].code));
        // }
        // for (var i = 0; i < res.data.length; i++) {
        //     $('.costType:eq('+i+') option[value="'+res.data[i].costType+'"]').prop("selected",true);
        // }
        // form.render('select');
    }
});
function   getCost(){
    var  cost1= getdictionary(5,19)
    var cost=new Array();
    for(let i in cost1){
        cost.push(cost1[i])
    }
    return cost

}
//---附件
table.render({
    elem: '#attachment'
    , data:annexList
    , toolbar: '#attachmenttoolbar'
    , cols: [[
        {field: 'fileName',event:'fileName', title: '文件名', fixed: true}
        , {field: 'uploadTime', title: '上传日期', fixed: true}
        , {fixed: 'right', width: 180, align: 'center', toolbar: '#attachmenteditor', title: '操作'}
    ]]
    , id: 'attachmenttableid'
    , height: 380
    , page: true
});
upload.render({
    elem: '#uploadfile'
    , url: 'billChange/uploadFile'
    , field: "uploadify"
    , accept: 'file'
    , multiple: true
    , auto: false
    , bindAction: '#testListAction'
    , choose: function (obj) {
        var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
        //读取本地文件
        obj.preview(function (index, file, result) {
            var tr = $(['<tr id="upload-' + index + '">'
                , '<td>' + file.name + '</td>'
                , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                , '<td>等待上传</td>'
                , '<td>'
                , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                , '</td>'
                , '</tr>'].join(''));

            //单个重传
            tr.find('.demo-reload').on('click', function () {
                obj.upload(index, file);
            });

            //删除
            tr.find('.demo-delete').on('click', function () {
                delete files[index]; //删除对应的文件
                tr.remove();
                uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
            });

            $("#uploadlist").append(tr);
        });
    }
    , parseData: function(res){
        return {
            "code": res.status,
            "count": res.total,
            "data": res.data
        };
    }
    , done: function (res, index, upload) {
        let data = res.data;
        for(var i in data){
            if (data[i].status) { //上传成功
                annexList.push(data[i]);
                var tr = $("#uploadlist").find('tr#upload-' + index)
                    , tds = tr.children();
                tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                tds.eq(3).html(''); //清空操作
                return delete this.files[index]; //删除文件队列已经上传成功的文件
            }
            this.error(index, upload);
        }
    }
    , error: function (index, upload) {
        var tr = $("#uploadlist").find('tr#upload-' + index)
            , tds = tr.children();
        tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
        tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
    }
});

table.on('toolbar(attachmenttable)', function (obj) {
    switch (obj.event) {
        case 'uploadfile':
            $("#uploadlist").html(""); //清空上传列表数据
            layer.open({
                type: 1,
                title: "文件上传",
                area: ['710px', '340px'],
                content: $("#attachmentupload")//引用的弹出层的页面层的方式加载修改界面表单
                , cancel: function (index, layero) {
                    table.reload('attachmenttableid', {data:annexList}); //点击关闭刷新表格
                }
            });
            break;
    }
    ;
});
table.on('tool(attachmenttable)', function (obj) {
    let data = obj.data;
    if (obj.event === 'download') { //下载
        let xmlHttpRequest = new XMLHttpRequest();
        let url = "wjinfo/downloadfile2?filename=" + data.filePath;
        xmlHttpRequest.open('GET', url, true);
        //设置请求头
        xmlHttpRequest.setRequestHeader("Content-type", "application/json")
        xmlHttpRequest.responseType = "blob";
        xmlHttpRequest.send(null);

        xmlHttpRequest.onload = function() {
            let content = xmlHttpRequest.response;
            // 组装a标签
            let elink = document.createElement("a");

            //设置文件下载路径
            elink.download = decodeURIComponent(data.fileName);
            elink.style.display = "none";
            let blob = new Blob([content], { type: 'application/force-download' });

            //解决下载不存在文件的问题，根据blob大小判断
            if(blob.size==0){
                layer.msg('服务器没找到此文件，请联系管理员!');
            }else{
                elink.href = window.URL.createObjectURL(blob);
                document.body.appendChild(elink);
                elink.click();
                document.body.removeChild(elink);
            }

        }
    } else if (obj.event === 'del') {
        layer.confirm('确认删除?', function (index) {
            obj.del();
            let id = data.id;
            for (var i = 0; i < annexList.length; i++) {
                if (annexList[i].id == id) {
                    annexList.splice(i, 1); // 将使后面的元素依次前移，数组长度减1
                    i--; // 如果不减，将漏掉一个元素
                    break;
                }
            }
            layer.msg("删除成功", {icon: 6});
            layer.close(index);
            table.reload('attachmenttableid', {data:annexList}); //ajax删除成功之后刷新表格
        });
    }else   if (obj.event === 'fileName') {
        onLineFile(data.filePath)
    }else if(obj.event === 'submit'){
        //获取头部表单数据
        let req = data.field;
        let billid=id;
        //获取附件数据
        let annexReqs = table.cache["attachmenttableid"];
        let datas = JSON.stringify(annexReqs);
        $.ajax({
            type:"POST",
            dataType:"json",
            contentType: 'application/json',
            data:datas,
            url:"billChange/add?id="+billid+"&type=2",
            success:function(res){
                if(res.status == 200){
                    layer.msg("保存成功", {icon: 6});
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
                return false;
            }
        });
    }
});

form.on('submit(form-element)', function (data) {
    //获取头部表单数据
    //获取附件数据
    let annexReqs = table.cache["attachmenttableid"];
    let datas = JSON.stringify(annexReqs);
    $.ajax({
        type:"POST",
        dataType:"json",
        contentType: 'application/json',
        data:datas,
        url:"billChange/addNew?id="+id+"&type=2",
        success:function(res){
            if(res.status == 200){
                layer.msg("保存成功", {icon: 6});
            }else {
                layer.msg(res.msg, {icon: 5});
            }
            return false;
        }
    });
})
//---操作日志
//权限判断
if (!LogLabel) {
    //有权限
    table.render({
        url:'billChange/selectBillExchangeLogsByPage?billNo='+id
        ,elem: '#otherwarehouselog'
        , data: data2
        , cols: [[
            {field: 'type', title: '操作类型', fixed: true}
            , {field: 'optioner', title: '操作员'}
            , {field: 'optionTime', title: '操作日期'}
            , {field: 'content', title: '修改内容'}
        ]]
        , id: 'logtableid'
        , height: 380
        , limit: 30//显示的数量
        , page: true
    });
}